package com.shelpe.services.scheduler.item.authorize;

import java.util.ArrayList;
import java.util.List;

import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("authorizeReader")
@Scope("step")
public class AuthorizeReader implements ItemReader<Long>{

	private final List<Long> mainInnerUserId = new ArrayList<Long>();
	
    private final Long pageNo;
    
    private final Long pageSize;
    
    private final Long subIndex;
    
    private final Long subPages;
	
	private int currentIndex;
	
    @Autowired
    public AuthorizeReader(@Value("#{jobParameters['pageNo']}")final Long pageNo, @Value("#{jobParameters['pageSize']}")final Long pageSize,
    		@Value("#{jobParameters['subIndex']}")final Long subIndex, @Value("#{jobParameters['subPages']}")final Long subPages,
    		@Value("#{jobParameters['userId']}")final Long userId, @Value("#{jobParameters['mainInnerUserId']}")final String mainInnerUserId){
    	
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        this.subIndex = subIndex;
        this.subPages = subPages;
    	this.currentIndex = 0;
    	if(mainInnerUserId != null){ 
            String[] innerUserId = mainInnerUserId.split(",");
            if(innerUserId != null && innerUserId.length > 0){
            	for(int i = 0; i < innerUserId.length; i++){
            		this.mainInnerUserId.add(Long.valueOf(innerUserId[i]));
            	}
            }
    	}
    }
	
	@Override
	public Long read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
		// TODO Auto-generated method stub
		Long firstThread = 0L;
		
		if(pageNo != null && pageNo.equals(firstThread) && 
				subIndex != null && subIndex.equals(firstThread) &&
				mainInnerUserId.size() > 0 && currentIndex < mainInnerUserId.size()){
			
			Long userId = mainInnerUserId.get(currentIndex);
			currentIndex++;
			
			return userId;
		}
		
		return null;
	}

}
